package com.chilly.io;

import org.junit.jupiter.api.Test;

import java.io.*;

/**
 * 缓冲流的正确姿势
 * Created by Chilly Cui on 2020/9/24.
 */
public class BufferedRightDemo {
    @Test
    void testRight() {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(new File("c:/env/三国/视频.mp4")));
            bos = new BufferedOutputStream(new FileOutputStream(new File("c:/env/三国/视频Copy.mp4")));
            int len;
            byte[] data = new byte[8 * 1024];
            while ((len = bis.read(data)) != -1) {
                bos.write(data, 0, len);
            }
        } catch (IOException e) {
            System.out.println(e);
        } finally {
            // finally块中关闭流，确保资源一定被关闭
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    System.out.println(e);
                }
            }

            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    System.out.println(e);
                }
            }
        }
    }
}
